<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
/**
 * 功    能：结合ThinkSDK完成腾讯,新浪微博,人人等用户的第三方登录
 * 修改日期：2013-12-11
 */

namespace Api\Controller;

use Common\Controller\HomebaseController;

class OauthController extends HomebaseController
{

    public function _initialize()
    {
    }

    // 第三方登录地址
    public function login($type = null)
    {
        empty($type) && $this->error('参数错误');
        session('login_http_referer', $_SERVER["HTTP_REFERER"]);
        //加载ThinkOauth类并实例化一个对象
        $sns = \ThinkOauth::getInstance($type);
        //跳转到授权页面
        redirect($sns->getRequestCodeURL());
    }

    // 第三方登录授权回调地址
    public function callback($type = null, $code = null)
    {

        (empty($type)) && $this->error('参数错误');

        if (empty($code)) {
            redirect(__ROOT__ . "/");
        }

//        微信小程序支付
        if ($type == 'wxpay') {
            $postStr = $GLOBALS['HTTP_RAW_POST_DATA']; // 这里拿到微信返回的数据结果
            file_put_contents("./wx.txt", $postStr, FILE_APPEND);

            $getData = $this->xmlstr_to_array($postStr); // 为了方便我就直接把结果转成数组，看个人爱好了

            if (($getData['total_fee']) && ($getData['result_code'] == 'SUCCESS')) {
                $osn = trim($getData['out_trade_no']);
                $res = M("Reward")->where(array(
                    "sn_no" => $osn
                ))->find();

                if ($res && $res['status'] == 0) {
                    M("Reward")->where(array(
                        "sn_no" => $osn
                    ))->save(array("status" => 1, 'pay_time' => time()));
                }
                echo 'success';
            } else {

                //加载ThinkOauth类并实例化一个对象
                $sns = \ThinkOauth::getInstance($type);

                //腾讯微博需传递的额外参数
                $extend = null;
                if ($type == 'tencent') {
                    $extend = array('openid' => I("get.openid"), 'openkey' => I("get.openkey"));
                }
                //请妥善保管这里获取到的Token信息，方便以后API调用
                //调用方法，实例化SDK对象的时候直接作为构造函数的第二个参数传入
                //如： $qq = ThinkOauth::getInstance('qq', $token);
                $token = $sns->getAccessToken($code, $extend);
                //获取当前登录用户信息
                if (is_array($token)) {
                    $user_info = A('Type', 'Event')->$type($token);
                    $session_oauth_bang = session('oauth_bang');
                    if (!empty($session_oauth_bang)) {
                        $this->_bang_handle($user_info, $type, $token);
                    } else {
                        $this->_login_handle($user_info, $type, $token);
                    }
                } else {
                    $this->success('登录失败！', $this->_get_login_redirect());
                }
            }

        }
    }

    // 第三方账号绑定
    public function bang($type = "")
    {
        if (sp_is_user_login()) {
            empty($type) && $this->error('参数错误');
            //加载ThinkOauth类并实例化一个对象
            import("ThinkOauth");
            $sns = \ThinkOauth::getInstance($type);
            //跳转到授权页面
            session('oauth_bang', 1);
            redirect($sns->getRequestCodeURL());
        } else {
            $this->error("您还没有登录！");

        }
    }

    /**
     * 获取登录跳转地址
     */
    private function _get_login_redirect()
    {
        $session_login_http_referer = session('login_http_referer');
        return empty($session_login_http_referer) ? __ROOT__ . "/" : $session_login_http_referer;
    }

    /**
     *  处理绑定第三方账号
     */
    private function _bang_handle($user_info, $type, $token)
    {

        $current_uid = sp_get_current_userid();
        $oauth_user_model = M('OauthUser');
        $type = strtolower($type);
        $find_oauth_user = $oauth_user_model->where(array("from" => $type, "openid" => $token['openid']))->find();
        $need_bang = true;
        if ($find_oauth_user) {

            if ($find_oauth_user['uid'] == $current_uid) {
                $this->error("您之前已经绑定过此账号！", U('user/profile/bang'));
                exit;
            } else {
                $this->error("该帐号已被本站其他账号绑定！", U('user/profile/bang'));
                exit;
            }

        }

        if ($need_bang) {

            if ($current_uid) {
                //第三方用户表中创建数据
                $new_oauth_user_data = array(
                    'from' => $type,
                    'name' => $user_info['name'],
                    'head_img' => $user_info['head'],
                    'create_time' => date("Y-m-d H:i:s"),
                    'uid' => $current_uid,
                    'last_login_time' => date("Y-m-d H:i:s"),
                    'last_login_ip' => get_client_ip(0, true),
                    'login_times' => 1,
                    'status' => 1,
                    'access_token' => $token['access_token'],
                    'expires_date' => (int)(time() + $token['expires_in']),
                    'openid' => $token['openid'],
                );
                $new_oauth_user_id = $oauth_user_model->add($new_oauth_user_data);
                if ($new_oauth_user_id) {
                    $this->success("绑定成功！", U('user/profile/bang'));
                } else {
                    $this->error("绑定失败！", U('user/profile/bang'));
                }
            } else {
                $this->error("绑定失败！", U('user/profile/bang'));
            }

        }

    }

    /**
     *  处理第三方登陆
     * qq登录：tencent
     * 微信登录：wx
     */
    private function _login_handle($user_info, $type, $token)
    {
        $oauth_user_model = M('OauthUser');
        $type = strtolower($type);
        $find_oauth_user = $oauth_user_model->where(array("from" => $type, "openid" => $token['openid']))->find();
        $return = array();
        $local_username = "";
        $need_register = true;
        if ($find_oauth_user) {
            $find_user = M('Users')->where(array("id" => $find_oauth_user['uid']))->find();
            if ($find_user) {
                $need_register = false;
                if ($find_user['user_status'] == '0') {
                    if ($type == 'wx') {
                        return array('status' => -1, 'msg' => '您可能已经被列入黑名单，请联系网站管理员!', 'result' => '');
                    } else {
                        $this->error('您可能已经被列入黑名单，请联系网站管理员！');
                        exit;
                    }
                } else {
                    if ($type == 'wx') {
                        return array('status' => 1, 'msg' => '登陆成功', 'result' => $find_oauth_user['id']);
                    } else {
                        session('user', $find_user);
                        redirect($this->_get_login_redirect());
                    }
                }
            } else {
                $need_register = true;
            }
        }

        if ($need_register) {
            //本地用户中创建对应一条数据
            $new_user_data = array(
                'user_nicename' => $user_info['name'],
                'avatar' => $user_info['head'],
                'last_login_time' => date("Y-m-d H:i:s"),
                'last_login_ip' => get_client_ip(0, true),
                'create_time' => date("Y-m-d H:i:s"),
                'user_status' => '1',
                "user_type" => '2',//会员
            );
            $users_model = M("Users");
            $new_user_id = $users_model->add($new_user_data);

            if ($new_user_id) {
                //第三方用户表中创建数据
                $new_oauth_user_data = array(
                    'from' => $type,
                    'name' => $user_info['name'],
                    'head_img' => $user_info['head'],
                    'create_time' => date("Y-m-d H:i:s"),
                    'uid' => $new_user_id,
                    'last_login_time' => date("Y-m-d H:i:s"),
                    'last_login_ip' => get_client_ip(0, true),
                    'login_times' => 1,
                    'status' => 1,
                    'access_token' => $token['access_token'],
                    'expires_date' => (int)(time() + $token['expires_in']),
                    'openid' => $token['openid'],
                );
                $new_oauth_user_id = $oauth_user_model->add($new_oauth_user_data);
                if ($new_oauth_user_id) {
                    if ($type == 'wx') {
                        return array('status' => 1, 'msg' => '登陆成功', 'result' => $new_oauth_user_id);
                    } else {
                        $new_user_data['id'] = $new_user_id;
                        session('user', $new_user_data);
                        redirect($this->_get_login_redirect());
                    }
                } else {
                    $users_model->where(array("id" => $new_user_id))->delete();
                    if ($type == 'wx') {
                        return array('status' => -1, 'msg' => '登陆失败', 'result' => '');
                    } else {
                        $this->error("登陆失败", $this->_get_login_redirect());
                    }
                }
            } else {
                if ($type == 'wx') {
                    return array('status' => -1, 'msg' => '登陆失败', 'result' => '');
                } else {
                    $this->error("登陆失败", $this->_get_login_redirect());
                }
            }

        }

    }

    /**
     * CURL请求
     * @param $url 请求url地址
     * @param $method 请求方法 get post
     * @param null $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug 调试开启 默认false
     * @return mixed
     */
    function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
        //return array($http_code, $response,$requestinfo);
    }

    /**
     * 微信小程序用户登录
     */
    public function wxLogin()
    {

        $wxAppid = C("THINK_SDK_WEIXIN.APP_KEY");
        $wxSecret = C("THINK_SDK_WEIXIN.APP_SECRET");
        $js_code = I('js_code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $wxAppid . "&secret=" . $wxSecret . "&js_code={$js_code}&grant_type=authorization_code";
        $return = $this->httpRequest($url, 'GET');
        $result = json_decode($return);
        $openid = $result->openid;

        if (!empty($openid)) {

            $token['access_token'] = '1234';
            $token['expires_in'] = '1';
            $token['openid'] = $openid;
            $user['name'] = I('nickName', '');;
            $user['head'] = I('avatarUrl', '');
            $result = $this->_login_handle($user, 'wx', $token);
            if ($result['status'] == 1) {
                exit(json_encode(array('status' => 1, 'msg' => '登录成功', 'result' => $result['result'])));
            } else {
                exit(json_encode(array('status' => -1, 'msg' => '登录失败', 'result' => $result)));
            }
        } else {
            exit(json_encode(array('status' => -1, 'msg' => '非法登录', 'result' => '')));
        }

    }
}